package com.wyj.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1、打开一个服务端nio通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //    2、绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",9999));
        //    3、修改通道为非阻塞。默认是阻塞的
        serverSocketChannel.configureBlocking(false);

        //4、死循环监听事件
        while (true) {
            //如果有客户端连接那么会返回具体的SocketChannel，否则返回null
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (null == socketChannel) {
                System.out.println("ServerSocketChannel没有接收到客户端连接，去干别的事情了···");
                Thread.sleep(5000);
                continue;
            }
            //5、获取接收到的客户端消息
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //读取到的数据的有效字节数
            int read = socketChannel.read(byteBuffer);
            System.out.println("ServerSocketChannel接收到客户端连接，接收到消息：" + new String(byteBuffer.array(), 0, read, StandardCharsets.UTF_8));
            //    6、向客户端返回数据
            socketChannel.write(ByteBuffer.wrap("这是服务端返回的消息···".getBytes(StandardCharsets.UTF_8)));
            //    7、释放资源
            socketChannel.close();

        }
    }
}
